﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Web;
using System.IO.Compression;
using System.Xml;

namespace WeatherGod
{
    class HttpWeb
    {
        private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727)";

        #region GET
        public static string HttpGETRequest(string url, int? timeout, string referer, string userAgent, CookieContainer cookies)
        {
            string html = string.Empty;

            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/QVOD, application/QVOD, application/xaml+xml, application/x-ms-xbap, application/x-ms-application, */*";
            request.Referer = referer;
            request.Headers.Add("Accept-Language", "zh-CN,en-us;q=0.5");
            request.Headers.Add("Accept-Encoding", "gzip, deflate"); //压缩stream
            request.Timeout = 15000; //15秒
            if (!string.IsNullOrEmpty(userAgent))
            {
                request.UserAgent = userAgent;
            }
            else
            {
                request.UserAgent = DefaultUserAgent;
            }
            if (timeout.HasValue)
            {
                request.Timeout = timeout.Value;
            }
            if (cookies != null)
            {
                request.CookieContainer = cookies;
            }
            HttpWebResponse iResponse = request.GetResponse() as HttpWebResponse;
            if (iResponse.StatusCode == HttpStatusCode.OK)
            {
                html = DecompressResponseContent(iResponse);
            }
            return html;
        }
        public static string getWeiboQunHtmlViaHttpGET(string uid, string gsid, string qunid)
        {
            string html = string.Empty;
            string user_agent = string.Empty;

            string requestURL = "http://weibo.cn/" + uid + "/qun/detail/" + qunid + "?vt=4&gsid=" + gsid;
            //http://weibo.cn/search/?vt=4&gsid=" + gsid;
            string referer = "http://weibo.cn/" + uid + "/qun/selectQun/?vt=4&gsid=" + gsid;

            CookieContainer cookies = new CookieContainer();
            cookies.Add(new Uri("http://weibo.cn/"), new Cookie("gsid_CTandWM", gsid));
            cookies.Add(new Uri("http://weibo.cn/"), new Cookie("_WEIBO_UID", uid));

            return HttpGETRequest(requestURL, 15000, referer, user_agent, cookies);

        }
        public static string getPM25DataViaHttpGet()
        {
            string requestURL = "http://www.aqicn.info/?city=all";
            string referer = requestURL;
            string user_agent = string.Empty;
            CookieContainer cookies = new CookieContainer();
            return HttpWeb.HttpGETRequest(requestURL, 60000, referer, user_agent, cookies);
        }
        public static XmlDocument getWeatherPlaceViaHttpGet(string place)
        {
            string xml_html = string.Empty;
            XmlDocument doc = new XmlDocument();
            string requestURL = "http://flash.weather.com.cn/wmaps/xml/" + place + ".xml";
            xml_html = HttpGetRequestForWeather(requestURL);
            if (!string.IsNullOrEmpty(xml_html) && !xml_html.Contains("DOCTYPE html"))
            {
                doc.LoadXml(xml_html);
                return doc;
            }
            else
            {
                return null;
            }
        }
        public static string HttpGetRequestForWeather(string requestURL)
        {
            string html = string.Empty;
            string userAgent = "Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1";

            string referer = string.Empty;
            string user_agent = string.Empty;

            HttpWebRequest request = WebRequest.Create(requestURL) as HttpWebRequest;
            request.Method = "GET";
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            request.Referer = referer;
            request.Headers.Add("Accept-Language", "zh-CN,en-us;q=0.8");
            request.Headers.Add("Accept-Encoding", "gzip, deflate"); //压缩stream
            request.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3"); //字符集
            request.Timeout = 60000; //15秒
            request.UserAgent = userAgent;

            HttpWebResponse iResponse = request.GetResponse() as HttpWebResponse;
            if (iResponse.StatusCode == HttpStatusCode.OK)
            {
                html = DecompressResponseContent(iResponse);
            }
            return html;

        }
        #endregion

        #region POST
        public static string HttpPOSTRequest(string url, IDictionary<string, string> parameters, int? timeout, string referer, string userAgent, Encoding requestEncoding, CookieContainer cookies)
        {
            string html = string.Empty;
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            if (requestEncoding == null)
            {
                throw new ArgumentNullException("requestEncoding");
            }
            HttpWebRequest request = null;
            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/QVOD, application/QVOD, application/xaml+xml, application/x-ms-xbap, application/x-ms-application, */*";
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Referer = referer;
            request.Headers.Add("Accept-Language", "zh-CN,en-us;q=0.5");
            request.Headers.Add("Accept-Encoding", "gzip, deflate"); //压缩stream
            request.Headers.Add("Cache-Control", "no-cache");
            request.Timeout = 30000; //15秒

            if (!string.IsNullOrEmpty(userAgent))
            {
                request.UserAgent = userAgent;
            }
            else
            {
                request.UserAgent = DefaultUserAgent;
            }
            if (timeout.HasValue)
            {
                request.Timeout = timeout.Value;
            }
            if (cookies != null)
            {
                request.CookieContainer = cookies;
                //request.CookieContainer = new CookieContainer();
                //request.CookieContainer.Add(cookies);
            }
            //如果需要POST数据  
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
                byte[] data = requestEncoding.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }

            HttpWebResponse iResponse = request.GetResponse() as HttpWebResponse;
            if (iResponse.StatusCode == HttpStatusCode.OK)
            {
                html = DecompressResponseContent(iResponse);
            }

            return html;

        }
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }
        public static string getWeiboSearchHtmlViaHttpPOST(string uid, string gsid, string keyword)
        {
            //getHtmlFromHttpPost(string uid, string gsid, string keyword)
            //getHtmlFromHttpPost("2487399871", "3_5bc278234d3121433a394e25d6b88b61a7c815b819", "天气");

            string html = string.Empty;

            string requestURL = "http://weibo.cn/search/?vt=4&gsid=" + gsid;

            CookieContainer cookies = new CookieContainer();
            cookies.Add(new Uri("http://weibo.cn/"), new Cookie("gsid_CTandWM", gsid));
            cookies.Add(new Uri("http://weibo.cn/"), new Cookie("_WEIBO_UID", uid));

            IDictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("keyword", HttpUtility.UrlEncode(keyword).ToUpper());
            parameters.Add("smblog", HttpUtility.UrlEncode("搜微博").ToUpper());

            string user_agent = string.Empty;

            string referer = "http://weibo.cn/search/?vt=4&gsid=" + gsid;

            html = HttpPOSTRequest(requestURL, parameters, 15000, referer, user_agent, Encoding.UTF8, cookies);
            return html;
        }
        #endregion

        #region gzip
        private static string DecompressResponseContent(HttpWebResponse response)
        {
            string responseBody = string.Empty;
            if (response.ContentEncoding.ToLower().Contains("gzip"))
            {
                using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        responseBody = reader.ReadToEnd();
                    }
                }
            }
            else if (response.ContentEncoding.ToLower().Contains("deflate"))
            {
                using (DeflateStream stream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress))
                {
                    using (StreamReader reader =
                        new StreamReader(stream, Encoding.UTF8))
                    {
                        responseBody = reader.ReadToEnd();
                    }
                }
            }
            else
            {
                using (Stream stream = response.GetResponseStream())
                {
                    using (StreamReader reader =
                        new StreamReader(stream, Encoding.UTF8))
                    {
                        responseBody = reader.ReadToEnd();
                    }
                }
            }
            return responseBody;
        }
        #endregion


    }
}
